const db = require('../../db/sql')
const {delay} = require('../../utils/delay')

async function addMenu(params, res) {
    let {rank_name, menu_name, path_name, parent_id} = params
    let rank_id
    if (parent_id) {
        rank_name = '二级菜单'
    } else {
        rank_name = '一级菜单'
    }
    console.log(params, '什么情况')
    // console.log(params.menuInfo,'88')
// 检查原始表格中是否已存在该菜单名
    const query1 = `SELECT * FROM origin_menu_list WHERE menu_name = '${menu_name}'`;
    const checkMenuNameExists = () => {
        console.log(query1, 'qq')
        return new Promise((resolve, reject) => {
            db.query(query1, (error, results) => {
                if (error) reject(error);
                else {
                    rank_id = results[0].rank_id
                    console.log(rank_id, '99')
                    parent_id = results[0].parent_id
                    resolve(results.length > 0);  // 返回布尔值
                }
            });
        });
    };

    const insertNewData = async () => {
// 如果不存在，则将数据插入新表格中
        const query2 = `INSERT INTO menulist (rank_id,menu_name, path_name, rank_name, parent_id)
                VALUES (${rank_id},'${menu_name}', '${path_name}', '${rank_name}', ${parent_id})`;
        // await delay(1200)
        console.log(query2, 'zz')
        return new Promise((resolve, reject) => {
            db.query(query2, (error, results) => {
                if (error) reject(error);
                else resolve(results.affectedRows > 0);  // 返回布尔值
            });
        });
    };
    let promiseTask = [checkMenuNameExists, insertNewData]

    try {
        // const [ menuNameExists,hasInsertedData] = [await checkMenuNameExists(),await insertNewData()];
        // let promiseRes = await promiseTask.reduce((prevTask, nextTask) => {
        //       return prevTask().then(() => nextTask())
        //   },)

        let menuNameExists = await checkMenuNameExists()
        console.log(rank_id, '嗯嗯')
        let hasInsertedData = await insertNewData()


        // console.log(promiseRes,'22')
        if (!hasInsertedData) {//!menuNameExists.isExist
            console.log(`无法将数据添加到 new_table 表格中。'' 在 original_table 表格中不存在。`);
            res.status(309).send({
                msg: '添加失效!!'
            })
        } else if (!menuNameExists) {//!hasInsertedData
            console.log(`无法将数据添加到 new_table 表格中。'' 已经存在于 new_table 表格中。`);
            res.status(305).send({
                msg: '菜单名或前端路径已存在'
            })
        } else {
            console.log(`数据已成功添加到 new_table 表格中。`);
            res.status(201).send({
                msg: '添加成功'
            })
        }
    } catch (error) {
        console.error('错误:', error.message);
        res.status(303).send({
            msg: '菜单名或前端路径已存在'
        })
    }
}

module.exports = addMenu
